package com.swxc.smartorder.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.swxc.smartorder.app.ConfigSPS;
import com.swxc.smartorder.broadcast.LocalBroadcastManager;
import com.swxc.smartorder.event.EventUtil;
import com.swxc.smartorder.event.SimpleEvent;
import com.swxc.smartorder.ui.activity.OrderDetailActivity;
import com.swxc.smartorder.ui.activity.WorkActivity;
import com.swxc.smartorder.utils.AppSharePreferenceMgr;
import com.swxc.smartorder.utils.PushUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.Objects;

import cn.jpush.android.api.JPushInterface;

/**
 * Author   Administrator
 * Date     2018/4/4
 * Desc     eg
 *
 * @author Administrator
 */
public class MyPushMessageReceiver extends BroadcastReceiver {
    private static final String TAG = "smartOrder_push";

    /**
     * 打印输出的数据
     *
     * @param bundle
     * @return
     */
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Log.d(TAG, "[MyPushMessageReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
            String pushString = bundle.getString(JPushInterface.EXTRA_EXTRA);

            String registionId = bundle.getString("cn.jpush.android.REGISTRATION_ID");
            if (registionId != null) {
                AppSharePreferenceMgr.put(context, ConfigSPS.REGISTRATION_ID, registionId);
            }
            String id = "";
            String title = "";
            String regId = "";
            int notifactionId = -1;
            try {
                JSONObject json = new JSONObject(pushString);
                id = json.optString("id");
                title = json.optString("title");

            } catch (JSONException e) {
                Log.e(TAG, "Get message extra JSON error!");
            }
            switch (Objects.requireNonNull(intent.getAction())) {
                case JPushInterface.ACTION_REGISTRATION_ID:
                    regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                    EventUtil.getInstance().postSticky(new SimpleEvent(SimpleEvent.REGISTRATION_ID, 0x0001, regId));
                    break;
                case JPushInterface.ACTION_MESSAGE_RECEIVED:
                    Log.d(TAG, "[MyPushMessageReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                    processCustomMessage(context, bundle);
                    break;
                case JPushInterface.ACTION_NOTIFICATION_RECEIVED:
                    Log.d(TAG, "[MyPushMessageReceiver] 接收到推送下来的通知");


                    break;

                //用户点开推送通知
                case JPushInterface.ACTION_NOTIFICATION_OPENED:
                    Intent detailIntent = new Intent(context, OrderDetailActivity.class);
                    Bundle detailBundle = new Bundle();
                    detailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    detailBundle.putLong("orderID", Long.parseLong(id));
                    detailIntent.putExtras(detailBundle);
                    context.startActivity(detailIntent);

                    break;
                case JPushInterface.ACTION_RICHPUSH_CALLBACK:
                    Log.d(TAG, "[MyPushMessageReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                    break;
                case JPushInterface.ACTION_CONNECTION_CHANGE:
                    boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                    Log.w(TAG, "[MyPushMessageReceiver]" + intent.getAction() + " connected state change to " + connected);
                    break;

                default:
                    Log.d(TAG, "[MyPushMessageReceiver] Unhandled intent - " + intent.getAction());
                    break;
            }


        } catch (Exception e) {

        }
    }

    /**
     * @param context
     * @param bundle
     */
    private void processCustomMessage(Context context, Bundle bundle) {

        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        Intent msgIntent = new Intent(WorkActivity.MESSAGE_RECEIVED_ACTION);
        msgIntent.putExtra(WorkActivity.KEY_MESSAGE, message);
        if (!PushUtils.isEmpty(extras)) {
            try {
                JSONObject extraJson = new JSONObject(extras);
                if (extraJson.length() > 0) {
                    msgIntent.putExtra(WorkActivity.KEY_EXTRAS, extras);
                }
            } catch (JSONException e) {

            }

        }
        LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
    }

}

